package water_qanxun_api.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import water_qanxun_api.controller.util.Code;
import water_qanxun_api.controller.util.Result;
import water_qanxun_api.domain.DevicesData;
import water_qanxun_api.service.DevicesService;
import water_qanxun_api.util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController // 标记为控制类
@CrossOrigin // 解决跨域问题
@RequestMapping("devices") // 指定请求路径
@Slf4j
public class DevicesController {
    @Autowired
    DevicesService devicesService; // 注入设备信息服务类
    
    @GetMapping("/getconfig/{mac}")
    public Result getDevicesConfig(@PathVariable String mac) {
        return new Result(Code.OK, devicesService.getDevicesConfig(mac));
    }
    
    @PutMapping("/updateconfig")
    public Result updateDevicesConfig(@RequestBody Map<String , String> dataMap) {
//        devicesService.updateDevicesConfig(devicesData);
        // 获取设备信息
        String mac = dataMap.get("mac");
        // 获取土壤湿度
        String soilHumi = dataMap.get("soilHumi");
        // 获取温度
        String temp = dataMap.get("temp");
        // 获取光照
        String light = dataMap.get("light");
        // 将soilHumi,temp和light解析成json字符串
        String config = String.format("{\"soilHumi\":%s,\"temp\":%s,\"light\":%s}", soilHumi, temp, light);
        devicesService.updateDevicesConfig(mac, config);
        return new Result(Code.OK, "操作成功");
    }
    
    // 插入设备信息
    @PutMapping
    public Result insertDevicesData(@RequestBody DevicesData devicesData, HttpServletRequest res) {
        Integer userId = JwtUtil.getIdFormRes(res);
        Boolean aBoolean = devicesService.insertDevicesData(devicesData, userId);
        return new Result(aBoolean ? Code.OK : Code.BUSINESS_ERR, "操作成功");
    }
    
    // 根据用户ID获取设备信息
    @GetMapping
    public Result getDevicesDataForUser(HttpServletRequest res) {
        Integer userId = JwtUtil.getIdFormRes(res);
        return new Result(Code.OK, devicesService.getDevicesDataForUser(userId));
    }
}
